<template>
  <div class="album-list">
    <div
      v-for="item in albums || []"
      :key="item.id"
      :class="`album-content ${selectAlbum?.id === item.id ? 'active' : ''}`"
    >
      <!-- <div class="album-imgs">
        <div
          v-for="url in item.toggleImgs"
          :key="url"
          :style="{ width: `${item.toggleImgs * 150}px` }"
        >
          <Image :src="url" lazy width="150px" height="200px" fit="cover" preview>
            <template #error>
              <Icon type="ios-image-outline" size="24" color="#ccc" />
            </template>
          </Image>
        </div>
      </div> -->
      <div class="album-preview" @click="handleSelectAlbum(item)">
        <!-- <div class="album-operate">
          <Tooltip content="下载当前图片" placement="left">
            <Icon color="#999" type="md-download" />
          </Tooltip>
          <div style="height: 15px"></div>
          <Tooltip content="复制当前图片" placement="left">
            <Icon color="#999" type="md-copy" />
          </Tooltip>
          <div style="height: 15px"></div>
          <Tooltip content="删除" placement="left">
            <Icon color="#999" type="md-trash" />
          </Tooltip>
          <div style="height: 15px"></div>
          <Poptip placement="right" width="400">
            <Tooltip content="替换相册包含的图片" placement="left">
              <Icon color="#999" type="md-repeat" />
            </Tooltip>
            <template #content>
              <uploadList />
            </template>
          </Poptip>
        </div> -->
        <Image :src="item.src" fit="contain" width="120px" height="80px" :alt="fit" />
        <!-- <img :src="item.src" :width="item.width" :height="item.height" /> -->
        <!-- <div class="album-page">
          <label>{{ index + 1 }}</label>
          <span>第{{ index + 1 }}页</span>
        </div> -->
      </div>
    </div>
    <div class="album-content">
      <Icon type="md-add" size="40" class="album-add" @click="handleAddAlbum()" />
    </div>
  </div>
  <div v-if="albums?.length === 0" class="album-empty">
    <div>暂无相册数据</div>
  </div>
  <!-- <Button icon="ios-add" @click="handleAddImg()">图片</Button> -->
  <canvas id="canvas-cache"></canvas>
</template>

<script setup name="Tools">
import { inject } from 'vue';
// import useAlbum from '@/hooks/useAlbum';
import useSelect from '@/hooks/select';
import useCreateImg from '@/hooks/useCreateImg';
import { defaultTml } from '@/config/constants/mock';
import { Spin } from 'view-ui-plus';
// import uploadList from '@/components/uploadList.vue';
import { removeBackground } from '@imgly/background-removal';

const fabric = inject('fabric');
const albumEditor = inject('albumEditor');
const { canvasEditor } = useSelect();
const canvas = new fabric.Canvas('canvas-cache');

const { createImage } = useCreateImg();
// onDeleteAlbum, onUpdateAlbum
const { albums, albumLoading, selectAlbum, onAddAlbum, onSelectAlbum } = albumEditor;
console.log(albums, 'albums');
const widthImg = 150,
  heightImg = 225;

const handleAddAlbum = async (data) => {
  let _data = data || defaultTml[0];
  let { width = widthImg, height = heightImg } = _data.attributes.json?.objects?.[0] || {};
  let _width = widthImg;
  let _heigth = (_width / width) * height;

  const img = await getImage(_data.attributes.json);

  let newData = {
    ..._data,
    id: Math.random(),
    width: _width,
    height: _heigth,
    src: img,
    // src: 'https://picsum.photos/200/300',
  };
  onAddAlbum(newData);
  handleSelectAlbum(newData);
};

const handleSelectAlbum = (item) => {
  onSelectAlbum(item.id);
  canvasEditor.loadJSON(JSON.stringify(item.attributes.json), Spin.hide);
};

// 生成图片
const getImage = (json) => {
  return new Promise((resolve) => {
    let { width, height } = json?.objects?.[0] || {};
    canvas.setDimensions({
      width: width,
      height: height,
    });
    canvas.loadFromJSON(json, () => {
      resolve(canvas.toDataURL({ format: 'png', quality: 1 }));
    });
  });
};

// 计算可替换图片数量，生成数字，替换图片
const transforJSON = () => {
  let albumData = defaultTml;

  let position = 0;
  albumData?.forEach(async (mock) => {
    mock.toggleImgs = [];
    mock?.attributes?.json?.objects?.forEach((item) => {
      if (item.fgToggle) {
        mock.toggleImgs.push(item.src);
        position++;
        item.position = position;
        item.srcCopy = item.src;
        item.src = createImage({
          width: item.width,
          height: item.height,
          backgroundColor: 'rgba(0, 0, 0, 0.3)',
          number: item.position,
        });
      }
    });
    handleAddAlbum({
      ...mock,
    });
  });
};

const init = async () => {
  // 加载图片（可以从 URL 或者 Blob 获取）
  const imageUrl =
    'https://img2.baidu.com/it/u=2781037149,3187912571&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1422';
  console.log(imageUrl, 'imageUrl');
  const image = await removeBackground(imageUrl);

  console.log(image, 'imageimage');
  const url = URL.createObjectURL(image);
  console.log(url);

  fabric.Image.fromURL(url, function (img) {
    // 释放object URL，避免内存泄漏
    URL.revokeObjectURL(url);
    console.log(img);

    addItem({
      src: img,
    });
  });
};

const addItem = async (target) => {
  canvasEditor.addBaseType(target.src, {
    scale: true,
  });
  // fabric.Image.fromURL(target.src, function (img) {
  //   canvasEditor.add(img);
  //   var path = new fabric.Path('M 10 10 L 100 10 L 50 100 z'); // 一个简单的三角形路径
  //   img.clipPath = path; // 设置裁剪路径为三角形
  //   canvasEditor.renderAll();
  // });
};

const getSVG = async (src) => {
  return new Promise((resolve) => {
    fabric.loadSVGFromURL(src, function (objects, options) {
      var obj = fabric.util.groupSVGElements(objects, options);

      resolve(obj);
    });
  });
};

const handleAddImg = async () => {
  const imgItem = await canvasEditor.createImgByElement({
    src: 'https://img2.baidu.com/it/u=2781037149,3187912571&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1422',
  });
  imgItem.set({
    // opacity: 0.5,
    left: 100,
    top: 50,
    // clipPath: new fabric.Circle({
    //   radius: 400,
    //   originX: 'center',
    //   originY: 'center',
    // }),
    // angle: 30,
  });
  // canvasEditor.addBaseType(imgItem, {
  //   scale: true,
  //   // clipPath: new fabric.Path('M 10 10 L 100 10 L 50 100 z'),
  // });

  const svg = await getSVG('http://127.0.0.1:8080/lizi.svg');
  console.log(svg.getScaledWidth(), svg.getScaledHeight());
  svg.set({
    scaleX: 4,
    scaleY: 4,
    originX: 'center',
    originY: 'center',
    fill: 'rgba(0, 0, 0, 0.2)',
  });

  canvasEditor.canvas.add(imgItem);
  canvasEditor.canvas.setActiveObject(imgItem);
  canvasEditor.canvas.renderAll();

  let currentImage = canvasEditor.canvas.getActiveObject();

  // const scale = currentImage.getScaled();
  // console.log(scale, ' scale');

  let width = currentImage.getScaledWidth(),
    height = currentImage.getScaledWidth();
  var clipPath = new fabric.Circle({
    radius: Math.min(width, height) / 2,
    top: 0,
    left: 0,
    // absolutePositioned: true,
    originX: 'center',
    originY: 'center',
  });
  console.log(width, height, clipPath);

  // var group = new fabric.Group([
  //   imgItem,
  //   // new fabric.Circle({ radius: 100, top: 0, left: 0, fill: ' orange', opacity: 0.5 }),
  // ]);
  currentImage.clipPath = svg;
  // currentImage.set('clipPath', clipPath);
  // canvasEditor.canvas.add(svg);
  canvasEditor.canvas.renderAll();

  // 创建一些对象
  // const rect = new fabric.Rect({ width: 300, height: 300, fill: 'red' });
  // const circle = new fabric.Circle({ radius: 150, fill: 'blue', left: 50 });
  // const text = new fabric.Text('Click me', { fontSize: 50, fill: 'white' });

  // 使用自定义Group，设置第二个元素(circle)为默认选中
  // const group = new fabric.Group([rect], {
  //   left: 100,
  //   top: 100,
  //   // canvas: canvasEditor.canvas,
  //   // defaultSelectedIndex: 1, // circle是第二个元素(索引1)
  // });
  // var clipPath = new fabric.Group([new fabric.Circle({ radius: 100, top: 0, left: -100 })], {
  //   left: 0,
  //   top: 0,
  // });

  // var clipPath = new fabric.CustomGroup(
  //   [
  //     new fabric.Circle({ radius: 70, top: -70, left: -70 }),
  //     new fabric.Circle({ radius: 40, left: -95, top: -95 }),
  //     new fabric.Circle({ radius: 40, left: 15, top: 15 }),
  //     // imgItem,
  //   ],
  //   {
  //     left: 0,
  //     top: -95,
  //     canvas: canvasEditor.canvas,
  //     defaultSelectedIndex: 1, // circle是第二个元素(索引1)
  //   }
  // );
  // var group = new fabric.Group([
  //   new fabric.Rect({ width: 100, height: 100, fill: 'red' }),
  //   new fabric.Rect({ width: 100, height: 100, fill: 'yellow', left: 100 }),
  //   new fabric.Rect({ width: 100, height: 100, fill: 'blue', top: 100 }),
  //   new fabric.Rect({ width: 100, height: 100, fill: 'green', left: 100, top: 100 }),
  // ]);

  // rect.clipPath = new fabric.Circle({
  //   radius: 100,
  //   top: -100,
  //   left: 0,
  //   originX: 'center',
  //   originY: 'center',
  // });

  // canvasEditor.canvas.add(rect);
  // canvasEditor.canvas.setActiveObject(rect);
  // canvasEditor.canvas.renderAll();
};

const sleep = async (time) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

onMounted(async () => {
  // await sleep(2000);

  // transforJSON();
  // init();

  // canvasEditor.canvas.on('mouse:dblclick', (e) => {
  //   console.log(e);
  // });

  canvasEditor.canvas.on('drop', function (options) {
    console.log(options);
    const file = options.e.dataTransfer.files[0];
    if (file.type.match('image.*')) {
      const reader = new FileReader();
      reader.onload = async function (f) {
        const imgItem = await canvasEditor.createImgByElement({
          src: f.target.result,
        });
        canvasEditor.addBaseType(imgItem, {
          scale: true,
        });
      };
      reader.readAsDataURL(file);
    }
  });
});
</script>

<style scoped lang="less">
.album-list {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;

  > .album-content {
    margin-top: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: var(--background-primary-color);
    border-radius: 6px;
    width: 130px;
    height: 100px;
    margin-left: 8px;
    cursor: pointer;

    &:nth-child(even) {
      margin-left: 12px;
    }

    .album-add {
      color: var(--primary-color);
    }

    .album-imgs {
      display: flex;
      align-items: center;
      flex: 1;
      overflow-x: scroll;
    }

    .album-preview {
      cursor: pointer;
      display: flex;
      align-items: center;

      .album-operate {
        display: flex;
        flex-direction: column;
        height: 100%;
        align-items: center;
        justify-content: center;
        flex: 1;
      }

      .album-page {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        flex: 1;

        label {
          font-size: 16px;
          color: #fff;
          width: 25px;
          height: 25px;
          border-radius: 13px;
          background-color: #ddd;
          text-align: center;
          line-height: 25px;
          margin-bottom: 8px;
        }

        span {
          font-size: 12px;
          color: #999;
        }
      }
    }

    &.active {
      border: 1px solid var(--primary-color);

      .album-page {
        label {
          background-color: #409eff;
        }

        span {
          color: #409eff;
        }
      }
    }
  }
}
.album-empty {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  color: #999;
}
#canvas-cache {
  position: absolute;
  top: -100000000px;
}
</style>
